/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.thienloc.omap.service.broadcast;

import com.thienloc.omap.entity.Broadcast;
import com.thienloc.omap.entity.BroadcastConfig;
import com.thienloc.omap.session.BroadcastFacade;
import com.thienloc.omap.util.Constant;
import java.math.BigInteger;
import java.net.Socket;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author GiangLT
 */
public class BroadcastProcessor implements Runnable {

    private BroadcastFacade broadcastFacade;
    private BroadcastConfig config;
    private Socket socket;
    private static final Logger logger = LoggerFactory.getLogger(BroadcastProcessor.class);

    public BroadcastProcessor(BroadcastFacade broadcastFacade, BroadcastConfig config, Socket socket) {
        this.broadcastFacade = broadcastFacade;
        this.config = config;
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            List<Broadcast> broadcasts = broadcastFacade.findByStatus("WAITING", config.getModuleName(), config.getSpeed());
            logger.info("Get {0} message from db", broadcasts.size());
            for (Broadcast broadcast : broadcasts) {
                StringBuilder sb = new StringBuilder();
                sb.append(broadcast.getId().intValue());
                sb.append(";");
                sb.append(broadcast.getMsisdn());
                sb.append(";");
                sb.append(config.getShortCode());
                sb.append(";");
                sb.append(broadcast.getContent());
                sb.append(";");
                sb.append(config.getOperator());
                sb.append("|");

//                PrintWriter osw = new PrintWriter(socket.getOutputStream());
                socket.getOutputStream().write(sb.toString().getBytes());
                logger.info(">> Sent broadcast req: {0}", sb.toString());

                broadcast.setStatus(Constant.broadcastStatuses.get("COMPLETED"));
                broadcast.setStatusCode(BigInteger.valueOf(2));
                broadcastFacade.edit(broadcast);
            }

        } catch (Exception ex) {
            logger.error("", ex);
        }
    }
}
